package com.tanhua.server.service;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.SoundApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class SoundService {

    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private SoundApi soundApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送语音
     * @param soundFile
     */
    public void addSound(MultipartFile soundFile) {

        try {
            //获取登陆用户id
            Long loginUserId = UserHolder.getUserId();
            //获取存储语音地址
            String soundUrl = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
            // 查询数据库中是否存在
            Sound oldSound = soundApi.findSoundByUserId(loginUserId);
            if (oldSound == null) {
                //创建对象,设置参数
                oldSound = new Sound();
                oldSound.setUserId(String.valueOf(loginUserId));
                oldSound.setSoundUrl(soundUrl);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String created = sdf.format(new Date());
                oldSound.setCreated(created);
                //添加数据
                String objectId = soundApi.addSound(oldSound);
                UserInfo userInfo = userInfoApi.findById(loginUserId);
                redisTemplate.opsForList().leftPush("th:" + userInfo.getGender(),objectId);
            } else {
                //删除旧的语音
                ossTemplate.delete(oldSound.getSoundUrl());
                //修改数据
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String created = sdf.format(new Date());
                oldSound.setCreated(created);
                oldSound.setSoundUrl(soundUrl);
                soundApi.updateSound(oldSound);
            }
        } catch (IOException e) {
            log.info("发送语音失败！",e);
            throw new TanHuaException("发送语音失败！");
        }
    }
}
